import { widgetManager } from '@/common/managers';
import { NMMeshBaseCommand } from '@/common/types';
import { nmAppLog } from '@/common/utils';
import i18n from '@/common/utils/i18next';
import { mesh } from '@/domain';
import { MessageTip } from '@amcax/base';
import { IChangeEvent } from '@rjsf/core';
import { CmdDialogForm, KEYBOARD_KEY } from 'nextcae-base';
import { useEffect, useState } from 'react';
import { schema, uiSchema } from './data';
import { ElementTypes, MethodType, TopoDialogProps } from './type';

// 面网格
function SurfaceMeshDialog({ title, onClose }: TopoDialogProps) {
  const [hintMessage] = useState('进入面网格命令,请选择面');
  const [isLoading, setIsLoading] = useState(false);
  const [formData, setFormData] = useState<any>({
    Curvature: {
      curvatureFactor: 0.2,
    },
    MeshSettings: {
      elementType: ElementTypes.Tri,
      method: MethodType.AFTDelaunay,
      // order: 1,
    },
    MeshSize: {
      growthRate: 1,
      maxLength: 20,
      minLength: 0,
    },
    Selection: { source: [] },
  });

  useEffect(() => {
    window.addEventListener('keyup', onKeyUp);
    return () => {
      window.removeEventListener('keyup', onKeyUp);
    };
  }, []);

  useEffect(() => {
    widgetManager.hint(hintMessage);
    return () => {
      widgetManager.hint();
    };
  }, [hintMessage]);

  const onKeyUp = (e: KeyboardEvent) => {
    // 点击键盘ESC退出命令
    if (e.key === KEYBOARD_KEY.ESC) {
      onClose();
    }
  };

  const handleSubmit = async (data) => {
    nmAppLog('handleSubmit====>:', data);
    if (data.Selection.source.length === 0) {
      return MessageTip.warning('请拾取Source面！');
    }
    if (data) {
      setIsLoading(true);
      const { Curvature, MeshSettings, MeshSize } = data;
      const params = {
        CurvatureFactor: Curvature?.curvatureFactor,
        GrowthRate: MeshSize?.growthRate,
        MaxSize: MeshSize?.maxLength,
        MinSize: MeshSize?.minLength,
        ElementType: MeshSettings?.elementType,
        MeshingMethod: MeshSettings?.method,
        MeshingDim: 2,
        SelectedEntities: data.Selection.source,
      };
      MeshSettings?.method === '' && delete params.MeshingMethod;
      try {
        await mesh.generate('general2D', params);
        setFormData((state) => ({ ...state, Selection: { source: [] } }));
      } catch (error) {
        nmAppLog(error);
      } finally {
        setIsLoading(false);
      }
      nmAppLog('handleSubmit:', data, params);
    }
  };
  const handleResultSelectChange = (data: IChangeEvent, id) => {
    nmAppLog('handleResultSelectChange:', data, id);
    if (data.formData) {
      // TODO 为何要做这样的处理
      if (id === 'root_MeshSettings_elementType') {
        let method = '';
        const type = data.formData.MeshSettings.elementType;
        if (ElementTypes.Tri === type) {
          method = MethodType.AFTDelaunay;
        }
        setFormData({
          ...data.formData,
          MeshSettings: {
            ...data.formData.MeshSettings,
            method,
          },
        });
      } else {
        setFormData(data.formData);
      }
    }
  };

  return (
    <CmdDialogForm
      title={title}
      formData={formData}
      titleIcon={'commands/mesh/auto'}
      onSubmit={handleSubmit}
      submitLoading={isLoading}
      onChange={handleResultSelectChange}
      schema={schema}
      extraUiSchema={uiSchema}
      onClose={onClose}></CmdDialogForm>
  );
}
// SurfaceMesh 面网格
export const cmdSurfaceMesh: NMMeshBaseCommand = {
  id: 'cmdSurfaceMesh',
  icon: 'commands/mesh/surface-mesh',
  label: 'command.mesh.surfaceMesh',
  create: (label: string, onClose: () => void, props) => (
    <SurfaceMeshDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
